package com.windmill.util;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

@SuppressWarnings("unchecked")
public class XMLUtils {
	public static Map<String,Object> parseMainPageXml(Reader read){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			SAXReader reader = new SAXReader();
			Document  document = reader.read(read);
			Element rootElm = document.getRootElement(); 
			map.putAll(parseAttribute(rootElm));// <QQHOME code="0"> 成功
			List<String> nodeList = new ArrayList<String>();
			for (Iterator<Node> it = rootElm.nodeIterator(); it.hasNext();) {  
		         Node elm =  it.next();
		         if(elm.getName()!=null&&!"".equals(elm.getName())){
		        	 nodeList.add(elm.getName());
		         }
			}
			for (String node : nodeList) {
				Element elem = rootElm.element(node);		
				Map<String, String> submap =  parseAttribute(elem);
				map.put(node, submap);//换卡箱。 炉位， 保险箱
				if(node.equals("changebox")||node.equals("stovebox")||node.equals("storebox")){
					map.put(node+"cards", getList(elem,"card"));
				}
			}       
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}
	public static List<Map<String, String>> parseList(Reader read,String nodeName) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document  document = reader.read(read);
		Element rootElm = document.getRootElement();		
		return getList(rootElm,nodeName);
	}
	@SuppressWarnings("rawtypes")
	private static List<Map<String, String>> getList(Element changebox,String childName) {
		List<Map<String, String>> list = new ArrayList<Map<String,String>>();
		 List nodes = changebox.elements(childName);  
	     for (Iterator it = nodes.iterator(); it.hasNext();) {  
	         Element elm = (Element) it.next();  
	         list.add(parseAttribute(elm));
		 }
		return list;
	}

	private static Map<String, String> parseAttribute(Element element) {
		Map<String,String> map = new HashMap<String,String>();
		for (Iterator<Attribute> it = element.attributeIterator(); it.hasNext();) {  
	    	  Attribute elm = it.next();  
	    	  map.put(elm.getName(), elm.getValue());   
	    } 
		return map;
	}

	public static void main(String[] args) throws Exception {
//		parseMainPageXml(new FileReader("src/com/share/util/mainPage.xml"));
		String[] tempGift = "".split("\\|");
		String[] sa = new String[0];
		System.out.println(sa.length);
		System.out.println(tempGift.length);
		System.out.println(tempGift[0].equals(""));
	}
    
}
